import React, { Component } from 'react';
import {
    View, Text, TextInput, StyleSheet, ScrollView, Dimensions
} from 'react-native';
import {connect} from 'react-redux';
import Toast, {DURATION} from 'react-native-easy-toast';

import { TABBAR_LABEL, ROUTERMAP } from '../util/constants';
import NccButton from "../components/Button";
import CommonTitleBar from "../components/CommonTitleBar";
import { request } from '../util';
import * as routerAction from '../actions/pageTransition';

const bottomHeight = 90; // 底部显示的高度
const {height} = Dimensions.get('window');
const miniExtract = 0.0015; // 最小提币数量

const RegExpAddress = new RegExp(/^$/);
const RegExpAmount = new RegExp(/^%$/);

interface Istate{
    numOfAccount: string,
    walletInfo?: Array<any>,
    avaliable?: number | string,
    coinType?: number | string,
    address?: string,
    amount: string,
    serviceFee: number, // 手续费
}

class Withdraw extends Component<any, Istate> {
    constructor(props) {
        super(props);
        this.state = {
            numOfAccount: '0',
            serviceFee: 0.00005,
            amount: ''
        }
    }

    componentDidMount() {
        const {navigation} = this.props;
        const type: string = navigation.getParam('type', 'no-type');
        const avaliable = navigation.getParam('avaliable', 0);
        this.setState({avaliable: avaliable, coinType: type});
        console.log('componentDidMount', type, avaliable);
    }

    componentWillReceiveProps(nextProps) {
        // 扫码页面跳转回来，传递扫码结果和扫码完成后跳转的页面
        console.log('componentWillReceiveProps', nextProps);
        // nextProps.scanCode
        if (nextProps.address) {
            this.setState({address: nextProps.address});
            // 然后这边清楚缓存
        }

    }

    toast = (content: string) => {
        this.refs.toast.show(content);
    }

    onAddressChange = (value) => {
        this.setState({address: value});
    }

    onAmountChange = (value: string) => {
        console.info('???', value, typeof value);
        value = value.replace(/\.{2,}/g, ".");
        let valueNum = Number(value)
        value = value.replace(/\.\d{2,}$/,value.substr(value.indexOf('.'),3));
        // let nvalue = String(value).replace(/^([1-9]\d*|0)(\.\d{1,4})?$/,"$1");
        console.log('---------------------------', value);
        // value = valueNum.toFixed(4);
        let {avaliable} = this.state;
        this.setState({amount: value, ttt: value});
        let numOfAccount = (valueNum - 0.00005).toFixed(4);
        if (avaliable && valueNum > avaliable) {
            this.toast('大于当前可用');
            return;
        }
        // if (value && value > miniExtract &&)
        if (valueNum - 0.00005 >= 0) {
            this.setState({numOfAccount: numOfAccount});
        }
    }

    // 处理钱包shuju 
    handleWalletInfo = (walletInfo) => {
        let data:Array<any> = [];
        const {
            BTC = 0, BTCLocked = 0, BTCAddress = 'BTC-0',
            ETH = 0, ETHLocked = 0, ETHAddress = 'ETH-0'
        } = walletInfo;
        let btcValue = BTC + BTCLocked + (ETH + ETHLocked) /10;
        let cnyValue = btcValue * 62584568;
        data[0] = {
            coinType: '0',
            fullName: 'BTC',
            amount: BTC + BTCLocked,
            restAmount: BTC,
            freezeAmount: BTCLocked,
            valuation: BTC + BTCLocked,
            address: BTCAddress
        };
        data[1] = {
            coinType: '1',
            fullName: 'ETH',
            amount: ETH + ETHLocked,
            restAmount: ETH,
            freezeAmount: ETHLocked,
            valuation: ETH + ETHLocked,
            address: ETHAddress
        }
        this.setState({walletInfo: data});
    }

    onPressAllBtn = () => {
        // const {}
        let {avaliable = 0, serviceFee} = this.state;
        console.log('pressAll', avaliable, serviceFee);
        let numOfAccount = Number(avaliable) - serviceFee;
        if (numOfAccount < 0) {
            numOfAccount = 0;
        }
        numOfAccount = numOfAccount.toFixed(4);
        this.setState({amount: Number(avaliable).toFixed(4), numOfAccount});
    }

    onEndAddressEditing = (value) => {
        console.log('onEndEditing', value);
    }

    onAmountEndEditing = (value) => {
        console.log('value====', value);
        if (value < miniExtract) {
            this.toast('提币数量需高于' + value);
            return;
        }
    }

    loadWalletInfo = (coinType) => {
        request('userqueryCoinAddr', {
            method: 'post',
            data: {coinType}
        }, false, (err, res) => {
            console.info('loadWalletInfo', err, res);
            if (err) {
                return null;
            }
            if (res) {
                this.handleWalletInfo(res.data);
            }
        })
    }

    turnToPage = (pageName: string, params?: Object) => {
        this.props.navigation.navigate(pageName, params);
    }

    scanCode = () => {
        this.props.setScanPageFrom(ROUTERMAP.balanceInfo);
        this.turnToPage(ROUTERMAP.scancode);
    }

    handleExtract = () => {
        let {coinType} = this.props;
        let {amount, address, avaliable} = this.state;
        console.log('amount, userCoinAddr, avaliable', amount, address, avaliable);
        // check data start
        if (!new RegExp(/\.\d{2,}$/).test(amount)) {
            return this.toast('amount is invalid');
        }
        if (avaliable && avaliable < amount) {
            return this.toast('amount is not avaliable');
        }

        if (!address) {
            return this.toast('address is invalid');
        }
        // if (!new )


        // check data end
        request('userDraw', {
            method: 'post',
            data: {
                userCoinAddr, amount, coinType
            }
        }, false, (err, res) => {
            if (res.retMsg === 'OK') {
                this.loadWalletInfo(coinType);
                // return Notification.success()
                console.log('提取成功');
            } else {
                if (res.retCode == '09') {
                    return console.error('提取失败，请检查余额是否足够');
                }
                return console.error('系统繁忙');
            }
        })

    }

    render() {
        const { navigation } = this.props;
        const type: string = navigation.getParam('type', 'no-type');
        const avaliable = navigation.getParam('avaliable', 0);
        return (
            <View>
                <CommonTitleBar nav={navigation} title={type + '充提币'} back />
                <ScrollView style={styles.scrollContent}>
                    <Text> {type} </Text>
                    <View>
                        <Text>可用</Text>
                        <Text>{avaliable} {type} </Text>
                    </View>
                    <Text>提币地址</Text>
                    <View style={styles.addressContent}>
                            <TextInput style={styles.addressInput} value={this.state.address} placeholder={'输入或长按粘贴地址'} 
                                onChangeText={this.onAddressChange} onEndEditing={this.onEndAddressEditing} underlineColorAndroid="transparent">
                            </TextInput>
                            <Text onPress={this.scanCode}>扫码</Text>
                            <Text>列表</Text>
                    </View>
                    <Text>数量</Text>
                    <View style={styles.amountContent}>
                        <TextInput value={this.state.amount} style={styles.amountInput} placeholder={'最小提币数量 0.015'} 
                            onChangeText={this.onAmountChange} onEndEditing={this.onAmountEndEditing} keyboardType={'numeric'}>
                        </TextInput>
                        <Text>{type}</Text>
                        <NccButton text={'全部'} onPress={this.onPressAllBtn}/>
                    </View>
                    <Text>{this.state.ttt}</Text>
                    <View>
                        <Text>手续费</Text>
                        <TextInput value={String(this.state.serviceFee)} editable={false}></TextInput>
                    </View>
                    <View style={styles.tip}>
                        <Text>
                            最小提币数量为：0.0015 {type}
                            为保证资金安全，当您账户安全策略变更、密码修改、使用新地址提币，我们会对提币进行人工审核，
                            请耐心等待工作人员电话或邮件联系。
                            请务必确认电脑及浏览器安全，防止信息被篡改或泄露。
                    </Text>
                    </View>
                </ScrollView>
                <View style={styles.bottomArea}>
                    <View style={{display: 'flex', flexDirection: 'row'}}>
                        <Text>到账数量</Text>
                        <Text>{Number(this.state.numOfAccount).toFixed(5)}  {type} </Text>
                    </View>
                    <NccButton text={'提币'} onPress={this.handleExtract    }/>
                </View>
                <Toast ref='toast' 
                            position='top'
                        />
            </View>
        )
    }
}


export default connect(
    (state) => ({
        scanPageFrom: state.page.scanPageFrom
    }),
    (dispatch) => ({
        setScanPageFrom: (page) => dispatch(routerAction.setScanPageFrom(page))
    })
)(Withdraw);

const styles = StyleSheet.create({
    scrollContent: {
        height: height - bottomHeight - 70
    },
    addressContent: {
        display: 'flex',
        flexDirection: 'row'
    },
    amountContent: {
        display: 'flex',
        flexDirection: 'row'
    },
    addressInput: {
        width: 300,
        height: 30,
        padding: 0
    },
    amountInput: {
        width: 300,
        height: 30
    },
    tip: {

    },
    bottomArea: {
        height: bottomHeight,
        backgroundColor: 'gray',
        alignSelf: 'flex-end',
        width: '100%'
    }
});
